<?php
// $Id: ConfigModule.php 590 2012-12-12 07:27:11Z tomqin@gmail.com $

/**
 * Part of the framework.
 *
 * @package     Module
 * @version     1.0
 * @copyright   Copyright (C) 2010-2012 SupeFun.com Inc.
 * @author      TomQin <tomqin@gmail.com>
 * @license     http://www.supefun.com/license/
 */

class ConfigModule {

    protected $namespace = '';
    protected $config = array();
    protected $source = 'config';

    public function __construct($namespace = '') {
        $this->source    = 'config';
        $this->namespace = $namespace;
        $config = Cache::get($this->source);
        isset($config[$this->namespace])
            $this->config = $config[$this->namespace];
    }

    /**
     * 设置一个配置选项
     *
     * @param string $name 配置项
     * @param mixed $value 配置值
     * @return ConfigModule
     */
    public function set($name, $value) {
        $this->config[$name] = $value;
        return $this;
    }

    /**
     * 返回当前配置的值
     *
     * @param string $name
     */
    public function get($name) {
        return isset($this->config[$name]) ? $this->config[$name]['value'] : '';
    }

    /**
     * 将数据持久化到数据库
     *
     * @return ConfigModule
     */
    public function flush() {
        $namespace = $this->namespace;
        $name = $value = $vtype = '';
        $sql  = Db::buildSql("REPLACE INTO %s (`name`, `namespace`, `value`, `vtype`) VALUES (?, ?, ?, ?)",
                        Db::table($this->source));
        $stmt = Db::prepare($sql);
        $stmt->bind_param('ssss', $name, $namespace, $value, $vtype);
        foreach($this->config as $name => $value){
            if(is_array($value)){
                $value = serialize($value);
                $vtype = 'array';
            }else{
                $vtype = 'string';
            }
            $stmt->execute();
        }
        $this->updateCache();
        return $this;
    }

    /**
     * 从数据库提取数据
     *
     * @return ConfigModule
     */
    protected function fetch(){
        $this->config = array();
        $sql = Db::buildSql("SELECT * FROM %s WHERE `namespace` = '%s'", Db::table($this->source), $this->namespace);
        $res = Db::query($sql);
        while($row = $res->fetch_assoc()){
            $this->config[$row['name']] = ($row['vtype'] == 'array' ? unserialize($row['value']) : $row['value']);
        }
        return $this;
    }

    /**
     * 更新缓存
     *
     * @return ConfigModule
     */
    protected function updateCache(){
        $cache = array();
        $sql = Db::buildSql("SELECT * FROM %s WHERE 1", Db::table($this->source));
        $res = Db::query($sql);
        while($row = $res->fetch_assoc()){
            $cache[$row['namespace']][$row['name']] = ($row['vtype'] == 'array' ? unserialize($row['value']) : $row['value']);
        }
        Cache::set($this->source, $cache);
        return $this;
    }
}
?>